package com.meirimoney.task;

import java.io.IOException;

import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.meiricai.sdk.utility.Common;
import com.meirimoney.app.MainActivity;
import com.meirimoney.business.User;
import com.meirimoney.business.UserInformation;
import com.meirimoney.sdk.models.AccessToken;
import com.meirimoney.service.MeiRiMoneyClient;

public class BalanceTask extends AsyncTask<AccessToken, Integer, Integer> {

	/***
	 * 当前任务的构造函数
	 * 
	 * @param c
	 *            当前的上下文信息
	 */
	public BalanceTask(Context c, TextView balancePanel) {
		this.context = c;
		if (this.context instanceof MainActivity) {
			this.progressBar = ((MainActivity) this.context).getProgressBar();
			this.refreshBtn = ((MainActivity) this.context).getRefreshBtn();
		}
		this.balancePanel = balancePanel;
	}

	@Override
	protected Integer doInBackground(AccessToken... params) {
		// 积分余额
		Integer balance = 0;
		try {
			balance = MeiRiMoneyClient.Instance.getIntegralBalance(params[0]);
		} catch (IOException e) {
			balance = -1;
		}
		return balance;
	}

	@Override
	protected void onPostExecute(Integer result) {
		if (result.intValue() == -1) {
			Common.networkWarn(this.context);
			result = User.get(this.context).getIntegralBalance();
		} else {
			User.get(this.context).setIntegralBalance(result);
		}
		this.balancePanel.setText(String.valueOf(result));
		this.done();
	}

	/**
	 * 启用刷新按钮
	 */
	public void done() {
		this.progressBar.setVisibility(View.GONE);
		this.refreshBtn.setVisibility(View.VISIBLE);
	}

	/**
	 * 当前上下文信息
	 */
	private Context context;

	/***
	 * 余额显示面板
	 */
	private TextView balancePanel;

	/**
	 * 刷新按钮
	 */
	private TextView refreshBtn;

	/**
	 * 进度条
	 */
	private ProgressBar progressBar;
}
